package com.txby.platformApi.component.web;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.jck.tools.MD5Util;
import com.txby.pf.common.annotation.SysLog;
import com.txby.pf.common.utils.Constant;
import com.txby.pf.common.utils.PageUtils;
import com.txby.pf.common.utils.Query;
import com.txby.pf.common.utils.R;
import com.txby.pf.common.validator.ValidatorUtils;
import com.txby.pf.common.validator.group.AddGroup;
import com.txby.pf.common.validator.group.UpdateGroup;
import com.txby.platformCore.entity.ProductDeviceInit;
import com.txby.platformCore.entity.ProductDeviceInitLot;
import com.txby.platformCore.entity.TxbySysApiUser;

/**
 * 商城订单商品评价
 */
@RestController
@RequestMapping("/spo/goodsEvaluation")
public class ShopGoodsEvaluationController  extends CommonController {
	
	/**
	 * 所有列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("spo:goodsEvaluation:list")
	public R list(@RequestParam Map<String, Object> params){
//		数据隔离
		String join="";
		
		String fsql="";
		
		
	/*	String sql="SELECT oge.id_ ogeId,oge.updateTime updateTime,sto.outTradeNo,go.outOrderNo,sp.name spName,g.name gName,gt.goodsTypeName gTypeName,oge.content content,oge.level,oge.isVisitor,oge.sickId FROM t_txby_sp_ordersGoodsEvaluation oge INNER JOIN  t_txby_sp_goodsOrders go INNER JOIN t_txby_sp_shopsThirdPayOrderRelation stor INNER JOIN  t_txby_sp_shopsThirdPayOrder sto on oge.ordersId=go.id_ and go.id_=stor.ordersId and stor.shopsThirdPayOrderId=sto.id_ "
				+ " INNER JOIN t_txby_sp_shops sp on  oge.shopsId=sp.id_  INNER JOIN  sys_dept d on d.dept_id=sp.deptId INNER JOIN  t_txby_sp_goodsType gt   INNER JOIN  t_txby_sp_baseGoods g on g.id_=oge.goodsId and gt.id_=oge.goodsTypeId  and g.goodsTypeId =gt.id_   " ;*/
		String sql="SELECT oge.updateTime updateTime,oge.id_ ogeId,sto.outTradeNo,oge.goodsId,oge.goodsTypeId,go.outOrderNo,sp.name spName,oge.content content,oge.level,oge.isVisitor,oge.sickId FROM t_txby_sp_ordersGoodsEvaluation oge INNER JOIN  t_txby_sp_goodsOrders go INNER JOIN t_txby_sp_shopsThirdPayOrderRelation stor INNER JOIN  t_txby_sp_shopsThirdPayOrder sto on oge.ordersId=go.id_ and go.id_=stor.ordersId and stor.shopsThirdPayOrderId=sto.id_ "
				+ " INNER JOIN t_txby_sp_shops sp on  oge.shopsId=sp.id_ left JOIN  sys_dept d on d.dept_id=sp.deptId where 1=1  " ;
		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
			 join=getJoinSqlBracket();
			 sql+=" and d.dept_id in "+join;
		}
		
		
		String gName=params.get("gName")==null?"":params.get("gName").toString();
		if(!ChkUtil.isEmptyAllObject(gName)){
			if (gName.contains("%") || gName.contains("_")) {
				gName = gName.trim().replace("%", "\\%").replace("_", "\\_");
				gName = "%" + gName + "%";
				sql += " and  oge.goodsName like #{pojo.gName} escape '\\'";
				params.put("gName", "%" + gName.trim() + "%");
			} else {
				gName = "%" + gName.trim() + "%";
				sql += " and oge.goodsName like #{pojo.gName} ";
				params.put("gName", "%" + gName.trim() + "%");
			}
		}
		sql += Query.getLastSortSql(params, " order by oge.updateTime  desc");
		//查询列表数据
		PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		for(Map m:pl.getResultList()){
			
			Long sickId=new Long(m.get("sickId").toString());
			Long isVisitor=new Long( m.get("isVisitor").toString());
			
			
			Long goodsId=new Long( m.get("goodsId").toString());
			Long goodsTypeId=new Long( m.get("goodsTypeId").toString());
			String uName="";
		     gName="";
			String gTypeName="";
			
			
			 
			if (isVisitor == 1) {
				sql = "SELECT DISTINCT CONCAT(u.name, '*', u.mobileNO) uName from t_txby_sp_ordersGoodsEvaluation oge,t_txby_sp_visitorUser u WHERE u.id_=oge.sickId and  oge.sickId="+sickId+"";
			    Map userData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
			    uName=userData.get("uName").toString();
			} else {
				sql = "SELECT DISTINCT CONCAT(sdi.sickName, '*', sdi.mobileNO) uName from t_txby_sp_ordersGoodsEvaluation oge,t_txby_sickDetailInfo sdi WHERE sdi.id_=oge.sickId and  oge.sickId="+sickId+" ";
			    Map userData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
			    uName=userData.get("uName").toString();
			}
			
			String  goodsTableName=getGoodsTableName(goodsTypeId.intValue());
		 sql="select g.name gName,gt.goodsTypeName gTypeName  from  t_txby_sp_goodsType gt,"+goodsTableName+" g   where  g.goodsTypeId =gt.id and g.id_="+goodsId+"  ";
		 
		   Map gData= (Map) this.mBaseDao.findBySqlUniqueObject(sql, null, null);
		   if(gData!=null){
			   gName=gData.get("gName").toString();
			   gTypeName=gData.get("gTypeName").toString();
		   }
          m.put("uName", uName);
          m.put("gName", gName);
          m.put("gTypeName", gTypeName);
			
//			System.out.println(JSON.toJSON(m));
		}
		
		
		
		PageUtils pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	
 
	
	/**
	 * 查询信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("spo:goodsEvaluation:info")
	public R info(@PathVariable("id") Long id){
		String sql="select t.sickAreaNO sickAreaNO,t.id_ id_,t.deviceSN deviceSN,t.bedNO bedNO,t.deptId deptId,t2.name deptName,t3.name sickAreaName from  t_txby_productDeviceInit t,sys_dept t2,sys_dept t3 where t2.dept_id=t.deptId and t.sickAreaNO=t3.dept_id and t.id_="+id+"" ;
		Map pro =  (Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return R.ok().put("pro", pro);
	}
	
	/**
	 * 保存信息
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SysLog("保存初始化")
	@RequestMapping("/save")
	@RequiresPermissions("spo:goodsEvaluation:save")
	public R save(@RequestBody ProductDeviceInit pd) throws IllegalAccessException, InvocationTargetException{
		ValidatorUtils.validateEntity(pd, AddGroup.class);
		String sql="select * from "+this.mBaseDao.tableName(ProductDeviceInit.class)+" where deviceSN='"+pd.getDeviceSN()+"'";
		ProductDeviceInit old=(ProductDeviceInit) this.mBaseDao.findBySqlUniqueObject(sql, ProductDeviceInit.class, null);
		if(old!=null){
	     old.setUpdater(getUserId().toString());
	     old.setUpdateTime(pd.getUpdateTime());
	     old.setBedNO(pd.getBedNO());
	     old.setSickAreaNO(pd.getSickAreaNO());
	     old.setDeptId(pd.getDeptId());
	     this.mBaseDao.updateObject(old);
	     ProductDeviceInitLot pdil=new ProductDeviceInitLot();
	     BeanUtils.copyProperties(pdil, old);
	     this.mBaseDao.updateObject(pdil);
		}else{
			sql="select * from "+this.mBaseDao.tableName(TxbySysApiUser.class)+"  where userName='"+pd.getDeviceSN()+"'";
//			db1e81c178f84c11f8dd19fa2b99c3f0
		/*	TxbySysApiUser  gau=(TxbySysApiUser) this.mBaseDao.findBySqlUniqueObject(sql, TxbySysApiUser.class, null);
			if(gau!=null) {
					gau.setPassWord(MD5Util.getMD5ofStr("db1e81c178f84c11f8dd19fa2b99c3f0", 2));
					this.mBaseDao.updateObject(gau);
					gau.setUpdateTime(new Date());
			}else{
					gau=new TxbySysApiUser();
					gau.setUserName(pd.getDeviceSN());
					gau.setPassWord(MD5Util.getMD5ofStr("db1e81c178f84c11f8dd19fa2b99c3f0", 2));
					this.mBaseDao.saveObject(gau);
				 
			}*/
			pd.setCreater(getUserId().toString());
			 pd.setUpdater(getUserId().toString());
			this.mBaseDao.saveObject(pd);
			 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
		     BeanUtils.copyProperties(pdil, pd);
		     this.mBaseDao.saveObject(pd);
		}
		return R.ok();
	}
	
	/**
	 * 修改设备初始化
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@SysLog("修改设备初始化")
	@RequestMapping("/update")
	@RequiresPermissions("spo:goodsEvaluation:update")
	public R update(@RequestBody ProductDeviceInit pd) throws IllegalAccessException, InvocationTargetException{
		ValidatorUtils.validateEntity(pd, UpdateGroup.class);
		String sql="select * from "+this.mBaseDao.tableName(ProductDeviceInit.class)+" where deviceSN='"+pd.getDeviceSN()+"'";
		ProductDeviceInit old=(ProductDeviceInit) this.mBaseDao.findBySqlUniqueObject(sql, ProductDeviceInit.class, null);
		if(old!=null){
	     old.setUpdater(getUserId().toString());
	     old.setUpdateTime(pd.getUpdateTime());
	     old.setBedNO(pd.getBedNO());
	     old.setSickAreaNO(pd.getSickAreaNO());
	     old.setDeptId(pd.getDeptId());
	     old.setSickAreaName(pd.getSickAreaName());
	     this.mBaseDao.updateObject(old);
		 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
	     BeanUtils.copyProperties(pdil, old);
	     this.mBaseDao.updateObject(pdil);
		}else{
			pd.setCreater(getUserId().toString());
			 pd.setUpdater(getUserId().toString());
			this.mBaseDao.saveObject(pd);
			 ProductDeviceInitLot pdil=new ProductDeviceInitLot();
		     BeanUtils.copyProperties(pdil, pd);
		     this.mBaseDao.saveObject(pdil);
		}
		
		return R.ok();
	}
	
	/**
	 * 删除初始绑定设备
	 */
	@SysLog("删除初始绑定设备")
	@RequestMapping("/delete")
	@RequiresPermissions("spo:goodsEvaluation:delete")
	public R delete(@RequestBody Long[] ids){
	    for(Long id:ids){
	    	this.mBaseDao.executeSql(" delete from t_txby_productDeviceInit where id_="+id+"", null);
	    }
		return R.ok();
	}
}
